package com.zjcode.cdcer.mq;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.consts.Consts.MQ_TYPE;
import com.chinatechstar.component.commons.entity.MqData;
import com.chinatechstar.component.commons.utils.SequenceGenerator;
import com.chinatechstar.component.commons.utils.UuidUtil;
import com.rabbitmq.client.Channel;
import com.zjcode.cdcer.config.MConsts;
import com.zjcode.cdcer.config.MConsts.SUB_DETAIL;
import com.zjcode.cdcer.config.VolumesConf;
import com.zjcode.cdcer.model.*;
import com.zjcode.cdcer.service.*;
import com.zjcode.cdcer.utils.Utils;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Component
@RabbitListener(queues = "fileimp_queue")
@Slf4j
public class FileImpMQListener {

    @Value("${studio.cer-report-file-in-disk}")
    private String cerReportFileInDisk;
    @Value("${studio.docker-deploy}")
    private boolean dockerDeploy = false;
    @Autowired
    private VolumesConf volumesConf;

    @Autowired
    private CerFileImpRecordService fileImpRecordService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TkmSysteminitImportInfoService systeminitImportInfoService;
    @Autowired
    private TkmEndoscopeDiagnoseNounInfoService endoscopeDiagnoseNounInfoService;
    @Autowired
    private TkmSysUserService tkmSysUserService;
    @Autowired
    private CerRecordSerialInfoService cerRecordSerialInfoService;
    @Autowired
    private TkmSysOrgService tkmSysOrgService;
    @Autowired
    private CerDetaildataImportInfoService cerDetaildataImportInfoService;
    @Autowired
    private SysDictService sysDictService;

    private static SequenceGenerator sequenceGenerator = new SequenceGenerator();

    @RabbitHandler
    public void messageHandler(String body, Message message, Channel channel) throws IOException {

        long msgTag = message
            .getMessageProperties()
            .getDeliveryTag();

        //log.info("msgTag={}", msgTag);
        //log.info("message={}", message.toString());
        //log.info("body={}", body);

        MqData mqData = JSONObject.parseObject(body, MqData.class);
        String type = mqData.getType();
        switch (type) {
            case MQ_TYPE.PARSE_CER_SYSTEM_DATA_INIT:
                // 解析农癌初始数据上报
                this.handleParseCerSystemDataInit(mqData);
                break;
            case MQ_TYPE.PARSE_GJ_CER_SYSTEM_DATA_INIT:
                // 解析农癌初始数据上报（国家系统来源）
                this.handleParseGJCerSystemDataInit(mqData);
                break;
            case MQ_TYPE.PARSE_GJ_CER_SYSTEM_DATA_INIT_OFFICIAL:
                // 解析农癌初始数据正式库（国家系统来源）
                this.handleParseGJCerSystemDataInitOfficial(mqData);
                break;
            case MQ_TYPE.PARSE_GJ_CER_DETAIL_DATA_INIT:
                // 解析农癌详情数据上报（国家系统来源）
                this.handleParseGJCerDetailData(mqData);
                break;
            case MQ_TYPE.PARSE_GJ_CER_DETAIL_OFFICIAL_DATA_INIT:
                // 解析农癌详情数据正式库（国家系统来源）
                this.handleParseGJCerDetailOfficial(mqData);
                break;
            case MQ_TYPE.PARSE_CER_DETAIL_REPORT_FILE:
                // 详情数据上报中的图片文件解析
                this.handleParseCerDetailReportFile(mqData);
                break;
            default:
                break;
        }

        // 告诉broker,消息已经被确认
        channel.basicAck(msgTag, true);

    }

    /**
     * 详情数据上报中的图片文件解析
     *
     * @param mqData
     */
    private void handleParseCerDetailReportFile(MqData mqData) {
        String ids = mqData.getContent();
        String userId = mqData.getTradeNo();
        log.info("ids={},userId={}", ids, userId);
        // ids=04cdc700c9054be4ab720c8f3c26dd65|d344b4cbdf374ddfb10b6b524ab9d1c4,
        // userId=999317657468350464

        // 获取extFlag
        String extFlag = sysUserService.findUserExtFlag(userId);

        // 通过ids获取到所有的上报记录
        String[] split = ids.split("\\|");
        List<CerFileImpRecord> list = fileImpRecordService.findAllByIds(Arrays.asList(split));

        // 针对每一条导入记录进行处理
        if (!CollectionUtils.isEmpty(list)) {

            List<CerFileImpRecord> type1 = new ArrayList<>();
            List<CerFileImpRecord> type2 = new ArrayList<>();

            // 先对数据进行拆分,将数据分成两组,一组为按照日期进行处理,一组为按照内镜号进行处理
            list.forEach(each -> {
                String filePath = each.getFilePath();
                // 获取真实的文件路径
                filePath = getRealFilePath(filePath);

                File file = new File(filePath);
                if (file.exists()) {
                    String fileName = file.getName();
                    // 通过+号拆分fileName
                    String[] temp1 = fileName.split("\\+");
                    String useful = temp1[2];
                    // 通过.号拆分useful
                    useful = useful.split("\\.")[0];
                    // 通过_号拆分useful
                    String[] temp2 = useful.split("\\_");
                    // 标记位:内镜/病理
                    String tag = temp2[0];
                    // 患者名称
                    String pName = temp2[1];
                    // 内镜日期/病理日期 | 内镜编号/病理编号
                    String specialField = temp2[2];
                    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");
                    try {
                        LocalDate ld = LocalDate.parse(specialField, fmt);
                        if (ld != null) {
                            // 格式为:内镜_患者_日期
                            type1.add(each);
                        } else {
                            // 格式为:内镜_患者_编码
                            type2.add(each);
                        }
                    } catch (Exception e) {
                        type2.add(each);
                    }

                }
            });

            // 处理类型1的数据
            handle4Type1(type1, extFlag);
            // 处理类型2的数据
            handle4Type2(type2, extFlag);

            log.info("所有导入数据处理完成!!");

            //list.forEach(each -> {
            //    ///Users/wlei/Desktop/Ld/software/files/upload/detailreport/20220820/20220820020037792+999317657468350464+内镜_患者姓名_20220820.jpg
            //    ///Users/wlei/Desktop/Ld/software/files/upload/detailreport/20220820/20220820020037792+999317657468350464+内镜_患者姓名_nj0001.jpg
            //    String filePath = each.getFilePath();
            //    // 获取真实的文件路径
            //    filePath = getRealFilePath(filePath);
            //
            //    File file = new File(filePath);
            //    if (file.exists()) {
            //        String fileName = file.getName();
            //        // 通过+号拆分fileName
            //        String[] temp1 = fileName.split("\\+");
            //        String useful = temp1[2];
            //        // 通过.号拆分useful
            //        useful = useful.split("\\.")[0];
            //        // 通过_号拆分useful
            //        String[] temp2 = useful.split("\\_");
            //        // 标记位:内镜/病理
            //        String tag = temp2[0];
            //        // 患者名称
            //        String pName = temp2[1];
            //        // 内镜日期/病理日期
            //        String date = temp2[2];
            //        // 内镜编号/病理编号
            //        String code = temp2[3];
            //
            //        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");
            //        DateTimeFormatter fmt2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            //
            //        if ("内镜".equals(tag)) {
            //            // 此处还要针对名称+诊疗日期进行次查询,如果查询到结果,则不再按照内镜编号进行查询
            //            // 将上述的date进行格式转换
            //            LocalDate ld = LocalDate.parse(date, fmt);
            //            String njdate = ld.format(fmt2);
            //            boolean b = njExecByNameAndTime(file, fileName, pName, njdate);
            //            if (!b) {
            //                njExecByNjNum(file, fileName, date, code, fmt, fmt2);
            //            }
            //        } else if ("病理".equals(tag)) {
            //            // 此处还要针对名称+诊疗日期进行次查询,如果查询到结果,则不再按照内镜编号进行查询
            //            // 将上述的date进行格式转换
            //            LocalDate ld = LocalDate.parse(date, fmt);
            //            String bldate = ld.format(fmt2);
            //            boolean b = blExecByNameAndTime(file, fileName, pName, bldate);
            //            if (!b) {
            //                blExecByBlNum(file, fileName, date, code, fmt, fmt2);
            //            }
            //        }
            //    }
            //});
        }

    }

    private void handle4Type1(List<CerFileImpRecord> type1, String extFlag) {
        // 解析type1中的数据
        type1.forEach(each -> {
            String filePath = each.getFilePath();
            // 获取真实的文件路径
            filePath = getRealFilePath(filePath);

            File file = new File(filePath);
            if (file.exists()) {
                String fileName = file.getName();
                // 通过+号拆分fileName
                String[] temp1 = fileName.split("\\+");
                String useful = temp1[2];
                // 通过.号拆分useful
                useful = useful.split("\\.")[0];
                // 通过_号拆分useful
                String[] temp2 = useful.split("\\_");
                // 标记位:内镜/病理
                String tag = temp2[0];
                // 患者名称
                String pName = temp2[1];
                // 内镜日期/病理日期
                String date = temp2[2];

                DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");
                DateTimeFormatter fmt2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                if ("内镜".equals(tag)) {
                    // 此处还要针对名称+诊疗日期进行次查询,如果查询到结果,则不再按照内镜编号进行查询
                    // 将上述的date进行格式转换
                    LocalDate ld = LocalDate.parse(date, fmt);
                    String njdate = ld.format(fmt2);
                    njExecByNameAndTime(file, fileName, pName, njdate, extFlag);
                } else if ("病理".equals(tag)) {
                    // 此处还要针对名称+诊疗日期进行次查询,如果查询到结果,则不再按照内镜编号进行查询
                    // 将上述的date进行格式转换
                    LocalDate ld = LocalDate.parse(date, fmt);
                    String bldate = ld.format(fmt2);
                    blExecByNameAndTime(file, fileName, pName, bldate, extFlag);
                }
            }
        });
    }

    private void handle4Type2(List<CerFileImpRecord> type2, String extFlag) {
        // 解析type2中的数据
        type2.forEach(each -> {
            String filePath = each.getFilePath();
            // 获取真实的文件路径
            filePath = getRealFilePath(filePath);

            File file = new File(filePath);
            if (file.exists()) {
                String fileName = file.getName();
                // 通过+号拆分fileName
                String[] temp1 = fileName.split("\\+");
                String useful = temp1[2];
                // 通过.号拆分useful
                useful = useful.split("\\.")[0];
                // 通过_号拆分useful
                String[] temp2 = useful.split("\\_");
                // 标记位:内镜/病理
                String tag = temp2[0];
                // 患者名称
                String pName = temp2[1];
                // 内镜号,病理号
                String code = temp2[2];

                if ("内镜".equals(tag)) {
                    njExecByNameAndCode(file, fileName, pName, code, extFlag);
                } else if ("病理".equals(tag)) {
                    blExecByNameAndCode(file, fileName, pName, code, extFlag);
                }
            }
        });
    }

    ///**
    // * 病理数据绑定,按照病理编号进行
    // *
    // * @param file
    // * @param fileName
    // * @param date
    // * @param code
    // * @param fmt
    // * @param fmt2
    // */
    //private void blExecByBlNum(File file,
    //                           String fileName,
    //                           String date,
    //                           String code,
    //                           DateTimeFormatter fmt,
    //                           DateTimeFormatter fmt2) {
    //    List<CerDetaildataImportInfo> records = cerDetaildataImportInfoService.selectByBlNum(code);
    //    if (!CollectionUtils.isEmpty(records)) {
    //        CerDetaildataImportInfo record = records.get(0);
    //        // 将病理图片放入指定位置中
    //        String path = generatReportFileSavePath(fileName);
    //        try {
    //            saveFile2Disk(getMultipartFile(file), path);
    //        } catch (IOException e) {
    //            throw new RuntimeException(e);
    //        }
    //        // 按照/拆分path
    //        String[] temp = path.split("\\/");
    //        String prefix = temp[temp.length - 2];
    //        // 设置url
    //        String url = prefix + "/" + fileName;
    //        // 设置内镜图片url
    //        record.setBlReportFileUrl(url);
    //        // 设置病理图片物理访问路径
    //        record.setBlReportFilePath(path);
    //        LocalDate ld = LocalDate.parse(date, fmt);
    //        // 设置病理报告
    //        record.setBlbgTime(ld.format(fmt2));
    //        // 标记已经上传
    //        record.setBlReportStatus(MConsts.ENDOSCOPIC_DIAGNOSIS_STATUS.IS_UPLOADED);
    //        // 移除错误信息中心,关于病理报告单未上传的提醒
    //        String errorMessage = record.getErrorMessage();
    //        // 按照|拆分
    //        String[] temp3 = errorMessage.split("\\|");
    //        List<String> errors = Arrays.asList(temp3);
    //        errorMessage = errors
    //            .stream()
    //            .filter(error -> !"病理报告单必须上传".equals(error))
    //            .collect(Collectors.joining(MConsts.Common.DELIMITER_CHARACTER));
    //        record.setErrorMessage(errorMessage);
    //        if (StringUtils.isEmpty(errorMessage)) {
    //            record.setErrorMessage("");
    //            record.setIsHaveError(0);
    //        }
    //
    //        int i = cerDetaildataImportInfoService.updateRecord(record);
    //        log.info(i > 0 ? "更新成功" : "更新失败");
    //    }
    //}

    private void blExecByNameAndCode(File file,
                                     String fileName,
                                     String name,
                                     String code,
                                     String extFlag) {
        List<CerDetaildataImportInfo> records = cerDetaildataImportInfoService.selectByBlNum(code,
                                                                                             extFlag);
        if (!CollectionUtils.isEmpty(records)) {
            // 遍历处理
            records.forEach(record -> {
                // 检查患者姓名能否匹配
                String hzxm = record.getName();
                if (Objects.equals(hzxm, name)) {
                    // 将病理图片放入指定位置中
                    String path = generatReportFileSavePath(fileName);
                    try {
                        saveFile2Disk(getMultipartFile(file), path);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    // 按照/拆分path
                    String[] temp = path.split("\\/");
                    String prefix = temp[temp.length - 2];
                    // 设置url
                    String url = prefix + "/" + fileName;
                    // 设置内镜图片url
                    record.setBlReportFileUrl(url);
                    // 设置病理图片物理访问路径
                    record.setBlReportFilePath(path);
                    // 标记已经上传
                    record.setBlReportStatus(MConsts.ENDOSCOPIC_DIAGNOSIS_STATUS.IS_UPLOADED);
                    // 移除错误信息中心,关于病理报告单未上传的提醒
                    String errorMessage = record.getErrorMessage();
                    // 按照|拆分
                    String[] temp3 = errorMessage.split("\\|");
                    List<String> errors = Arrays.asList(temp3);
                    errorMessage = errors
                        .stream()
                        .filter(error -> !"病理报告单必须上传".equals(error))
                        .collect(Collectors.joining(MConsts.Common.DELIMITER_CHARACTER));
                    record.setErrorMessage(errorMessage);
                    if (StringUtils.isEmpty(errorMessage)) {
                        record.setErrorMessage("");
                        record.setIsHaveError(0);
                    }

                    int i = cerDetaildataImportInfoService.updateRecord(record);
                    log.info(i > 0 ? "更新成功" : "更新失败");
                }
            });
        }
    }

    /**
     * 内镜数据绑定
     *
     * @param file
     * @param fileName
     * @param name
     * @param bldate
     * @param extFlag
     * @return
     */
    private void blExecByNameAndTime(File file,
                                     String fileName,
                                     String name,
                                     String bldate,
                                     String extFlag) {
        List<CerDetaildataImportInfo> records = cerDetaildataImportInfoService.selectByNameAndBlbgTime(
            name,
            bldate,
            extFlag);
        if (!CollectionUtils.isEmpty(records)) {

            records.forEach(record -> {
                // 将内镜图片放入指定位置中
                String path = generatReportFileSavePath(fileName);
                try {
                    saveFile2Disk(getMultipartFile(file), path);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                // 按照/拆分path
                String[] temp = path.split("\\/");
                String prefix = temp[temp.length - 2];
                // 设置url
                String url = prefix + "/" + fileName;
                // 设置内镜图片url
                record.setBlReportFileUrl(url);
                // 设置内镜图片物理访问路径
                record.setBlReportFilePath(path);
                // 标记已经上传
                record.setBlReportStatus(MConsts.ENDOSCOPIC_DIAGNOSIS_STATUS.IS_UPLOADED);
                // 移除错误信息中心,关于病理报告单未上传的提醒
                String errorMessage = record.getErrorMessage();
                // 按照|拆分
                String[] temp3 = errorMessage.split("\\|");
                List<String> errors = Arrays.asList(temp3);
                errorMessage = errors
                    .stream()
                    .filter(error -> !"内镜报告单必须上传".equals(error))
                    .collect(Collectors.joining(MConsts.Common.DELIMITER_CHARACTER));
                record.setErrorMessage(errorMessage);
                if (StringUtils.isEmpty(errorMessage)) {
                    record.setErrorMessage("");
                    record.setIsHaveError(0);
                }
                //内镜报告单必须上传
                int i = cerDetaildataImportInfoService.updateRecord(record);
                log.info(i > 0 ? "更新成功" : "更新失败");
            });
        }
    }

    /**
     * 内镜数据绑定,按照患者姓名,诊断日期进行
     *
     * @param file
     * @param fileName
     * @param name
     * @param njdate
     * @param extFlag
     * @return
     */
    private void njExecByNameAndTime(File file,
                                     String fileName,
                                     String name,
                                     String njdate,
                                     String extFlag) {
        List<CerDetaildataImportInfo> records = cerDetaildataImportInfoService.selectByNameAndNjzlTime(
            name,
            njdate,
            extFlag);
        if (!CollectionUtils.isEmpty(records)) {
            records.forEach(record -> {
                // 将内镜图片放入指定位置中
                String path = generatReportFileSavePath(fileName);
                try {
                    saveFile2Disk(getMultipartFile(file), path);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                // 按照/拆分path
                String[] temp = path.split("\\/");
                String prefix = temp[temp.length - 2];
                // 设置url
                String url = prefix + "/" + fileName;
                // 设置内镜图片url
                record.setReportFileUrl(url);
                // 设置内镜图片物理访问路径
                record.setReportFilePath(path);
                // 标记已经上传
                record.setNjReportStatus(MConsts.ENDOSCOPIC_DIAGNOSIS_STATUS.IS_UPLOADED);
                // 移除错误信息中心,关于病理报告单未上传的提醒
                String errorMessage = record.getErrorMessage();
                // 按照|拆分
                String[] temp3 = errorMessage.split("\\|");
                List<String> errors = Arrays.asList(temp3);
                errorMessage = errors
                    .stream()
                    .filter(error -> !"内镜报告单必须上传".equals(error))
                    .collect(Collectors.joining(MConsts.Common.DELIMITER_CHARACTER));
                record.setErrorMessage(errorMessage);
                if (StringUtils.isEmpty(errorMessage)) {
                    record.setErrorMessage("");
                    record.setIsHaveError(0);
                }
                //内镜报告单必须上传
                int i = cerDetaildataImportInfoService.updateRecord(record);
                log.info(i > 0 ? "更新成功" : "更新失败");
            });
        }
    }

    /**
     * 内镜数据绑定,按照内镜编号进行
     *
     * @param file
     * @param fileName
     * @param name
     * @param code
     */
    private void njExecByNameAndCode(File file,
                                     String fileName,
                                     String name,
                                     String code,
                                     String extFlag) {
        // 按照内镜编号查找对应的详情记录
        List<CerDetaildataImportInfo> records = cerDetaildataImportInfoService.selectByNjNum(code,
                                                                                             extFlag);
        if (!CollectionUtils.isEmpty(records)) {
            // 对结果进行遍历处理
            records.forEach(record -> {
                // 检查患者姓名能否匹配
                String hzxm = record.getName();
                if (Objects.equals(hzxm, name)) {
                    // 匹配,进行数据更新
                    // 将内镜图片放入指定位置中
                    String path = generatReportFileSavePath(fileName);
                    try {
                        saveFile2Disk(getMultipartFile(file), path);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    // 按照/拆分path
                    String[] temp = path.split("\\/");
                    String prefix = temp[temp.length - 2];
                    // 设置url
                    String url = prefix + "/" + fileName;
                    // 设置内镜图片url
                    record.setReportFileUrl(url);
                    // 设置内镜图片物理访问路径
                    record.setReportFilePath(path);
                    // 标记已经上传
                    record.setNjReportStatus(MConsts.ENDOSCOPIC_DIAGNOSIS_STATUS.IS_UPLOADED);
                    // 移除错误信息中心,关于病理报告单未上传的提醒
                    String errorMessage = record.getErrorMessage();
                    // 按照|拆分
                    String[] temp3 = errorMessage.split("\\|");
                    List<String> errors = Arrays.asList(temp3);
                    errorMessage = errors
                        .stream()
                        .filter(error -> !"内镜报告单必须上传".equals(error))
                        .collect(Collectors.joining(MConsts.Common.DELIMITER_CHARACTER));
                    record.setErrorMessage(errorMessage);
                    if (StringUtils.isEmpty(errorMessage)) {
                        record.setErrorMessage("");
                        record.setIsHaveError(0);
                    }
                    //内镜报告单必须上传
                    int i = cerDetaildataImportInfoService.updateRecord(record);
                    log.info(i > 0 ? "更新成功" : "更新失败");
                }
            });

        }
    }

    /**
     * 内镜数据绑定,按照内镜编号进行
     *
     * @param file
     * @param fileName
     * @param date
     * @param code
     * @param fmt
     * @param fmt2
     */
    //private void njExecByNjNum(File file,
    //                           String fileName,
    //                           String date,
    //                           String code,
    //                           DateTimeFormatter fmt,
    //                           DateTimeFormatter fmt2) {
    //    // 按照内镜编号查找对应的详情记录
    //    List<CerDetaildataImportInfo> records = cerDetaildataImportInfoService.selectByNjNum(code);
    //    if (!CollectionUtils.isEmpty(records)) {
    //        CerDetaildataImportInfo record = records.get(0);
    //        // 将内镜图片放入指定位置中
    //        String path = generatReportFileSavePath(fileName);
    //        try {
    //            saveFile2Disk(getMultipartFile(file), path);
    //        } catch (IOException e) {
    //            throw new RuntimeException(e);
    //        }
    //        // 按照/拆分path
    //        String[] temp = path.split("\\/");
    //        String prefix = temp[temp.length - 2];
    //        // 设置url
    //        String url = prefix + "/" + fileName;
    //        // 设置内镜图片url
    //        record.setReportFileUrl(url);
    //        // 设置内镜图片物理访问路径
    //        record.setReportFilePath(path);
    //        LocalDate ld = LocalDate.parse(date, fmt);
    //        // 设置内镜诊疗日期
    //        record.setNjzlTime(ld.format(fmt2));
    //        // 标记已经上传
    //        record.setNjReportStatus(MConsts.ENDOSCOPIC_DIAGNOSIS_STATUS.IS_UPLOADED);
    //        // 移除错误信息中心,关于病理报告单未上传的提醒
    //        String errorMessage = record.getErrorMessage();
    //        // 按照|拆分
    //        String[] temp3 = errorMessage.split("\\|");
    //        List<String> errors = Arrays.asList(temp3);
    //        errorMessage = errors
    //            .stream()
    //            .filter(error -> !"内镜报告单必须上传".equals(error))
    //            .collect(Collectors.joining(MConsts.Common.DELIMITER_CHARACTER));
    //        record.setErrorMessage(errorMessage);
    //        if (StringUtils.isEmpty(errorMessage)) {
    //            record.setErrorMessage("");
    //            record.setIsHaveError(0);
    //        }
    //        //内镜报告单必须上传
    //        int i = cerDetaildataImportInfoService.updateRecord(record);
    //        log.info(i > 0 ? "更新成功" : "更新失败");
    //    }
    //}

    /**
     * 将文件写入磁盘
     *
     * @param file
     * @param path
     * @throws IOException
     */
    private void saveFile2Disk(MultipartFile file, String path) throws IOException {
        File f = new File(path);
        if (f.exists()) {
            f.delete();
        }
        //将文件写入磁盘
        Files.write(Paths
                        .get(path)
                        .normalize()
                        .toAbsolutePath(), file.getBytes(), StandardOpenOption.CREATE_NEW);
    }

    private MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file",
                                             MediaType.MULTIPART_FORM_DATA_VALUE,
                                             true,
                                             file.getName(),
                                             (int) file.length(),
                                             file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

    /**
     * 生成内镜诊断报告单的存放路径
     *
     * @param fileName
     * @return
     */
    private String generatReportFileSavePath(String fileName) {
        // 日期目录
        String dirName = cerReportFileInDisk + DateFormatUtils.format(new Date(), "yyyyMMdd");
        File dir = new File(dirName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirName + "/" + fileName;
    }

    /**
     * 解析农癌初始数据上报
     *
     * @param mqData
     */
    private void handleParseCerSystemDataInit(MqData mqData) {
        // 解析农癌初始数据上报
        log.info("解析农癌初始数据上报");
        String tradeNo = mqData.getTradeNo();

        // 通过tradeNo查询数据库，获取数据
        CerFileImpRecord record = fileImpRecordService.findByTradeNo(tradeNo);
        // 获取文件所在位置
        String filePath = record.getFilePath();
        // 校正地址
        filePath = getRealFilePath(filePath);

        ImportParams params = new ImportParams();
        params.setTitleRows(1);

        // 解析excel
        List<TkmSystemInitImportData> list = ExcelImportUtil.importExcel(new File(filePath),
                                                                         TkmSystemInitImportData.class,
                                                                         params);

        // 数据过滤
        list = list
            .stream()
            .filter(each -> StringUtils.isNotEmpty(each.getName())
                && StringUtils.isNotEmpty(each.getNj_staff())
                // 内镜诊断必填
                && StringUtils.isNotEmpty(each.getNjzd())
                && StringUtils.isNotEmpty(each.getBlzd_staff()))
            .collect(Collectors.toList());

        // 将TkmSystemInitImportData转换成TkmSysteminitImportInfo
        List<TkmSysteminitImportInfo> importInfoList = list
            .stream()
            .map(each -> {
                TkmSysteminitImportInfo target = getSysteminitImportInfo(each);
                return target;
            })
            .collect(Collectors.toList());

        // 对需要导入的数据进行验证
        importInfoList
            .parallelStream()
            .forEach(each -> {
                List<String> errors = Utils.validateSysteminitImportInfoData(each);
                if (errors.size() > 0) {
                    each.setIsHaveError(1);
                    each.setErrorMessage(errors
                                             .stream()
                                             .collect(Collectors.joining("|")));
                } else {
                    each.setIsHaveError(0);
                    each.setErrorMessage("");
                }
            });

        // 获取extFlag
        String extFlag = sysUserService.findUserExtFlag(record.getCreateBy());

        // 检查是否需要显示诊断详情表
        importInfoList
            .parallelStream()
            .forEach(info -> {
                Map<String, Boolean> booleanMap = Utils.validateIsHighRisk(info);
                // 食管详情
                Boolean sg = booleanMap.get(SUB_DETAIL.SG);
                info.setIsShowSgDetail(sg ? 1 : 0);
                // 贲门详情
                Boolean bm = booleanMap.get(SUB_DETAIL.BM);
                info.setIsShowBmDetail(bm ? 1 : 0);
                // 胃详情
                Boolean wd = booleanMap.get(SUB_DETAIL.WD);
                info.setIsShowWDetail(wd ? 1 : 0);
                // 将以上三个详情信息放入extFlag2中
                String extFlag2 = Arrays
                    .asList(info.getIsShowSgDetail(),
                            info.getIsShowBmDetail(),
                            info.getIsShowWDetail())
                    .stream()
                    .map(each -> each.toString())
                    .collect(Collectors.joining("|"));
                info.setExtFlag2(extFlag2);

            });

        // 获取用户的省市县区机构的编码与名称
        TkmUserOrgAndRegions regionsAndOrg = tkmSysUserService.findUserRegionsAndOrg(record.getCreateBy());
        SysOrg userOrg = regionsAndOrg.getSysOrg();
        List<ZjcodeSysRegion> userRegions = regionsAndOrg.getRegions();

        // 执行数据插入前的准备工作
        importInfoList
            .stream()
            .forEach(each -> {
                each.setId(UuidUtil.get32UUID());
                each.setCreateBy(record.getCreateBy());
                each.setExtFlag(extFlag);
                each.setDeleted(0);
                each.setVersion(1);
                each.setInsertDatetime(new Date(System.currentTimeMillis()));
                each.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                // 放入省市县区数据
                if (userRegions.size() > 0) {
                    userRegions
                        .parallelStream()
                        .forEach(region -> {
                            String regionType = region.getRegionType();
                            switch (regionType) {
                                case "province":
                                    each.setProvinceId(region.getRegionCode());
                                    each.setProvinceName(region.getRegionName());
                                    break;
                                case "city":
                                    each.setCityId(region.getRegionCode());
                                    each.setCityName(region.getRegionName());
                                    break;
                                case "district":
                                    each.setDistrictId(region.getRegionCode());
                                    each.setDistrictName(region.getRegionName());
                                    break;
                            }
                        });
                }
                String orgId = userOrg
                    .getId()
                    .toString();

                // 放入用户机构数据
                each.setInstitutionId(orgId);
                each.setInstitutionName(userOrg.getOrgName());
                // 设置screening_id
                //screen_id生成规则,区域id+动态码
                //规则如下:医院的行政区划(6位)+医院的编号(2位)+年份(2位)+加上医院上报序列号(6位)
                if (userOrg.getOrgCode() != null) {
                    //医院的行政区划
                    String regionCode = tkmSysOrgService.getRegionCode(orgId) == null ? ""
                        : tkmSysOrgService.getRegionCode(orgId);
                    //医院的编号
                    String exFlag2 = tkmSysOrgService.getExFlag2(orgId) == null ? ""
                        : tkmSysOrgService.getExFlag2(orgId);

                    //年份
                    int year = LocalDate
                        .now()
                        .getYear();
                    String yearStr = String.valueOf(year);
                    yearStr = yearStr.substring(yearStr.length() - 2);

                    //医院上报序列号
                    //TODO:此循环不能使用parallelStream(),否则多线程跑会同时未拿到数据然后插入表，达不到预设效果
                    String strNum = getScreenId(orgId);
                    if (StringUtils.isEmpty(strNum)) {
                        insertData(orgId);
                        //拼接screen_id
                        String screenId = regionCode + exFlag2 + yearStr + "000001";
                        each.setScreeningId(screenId);
                    } else {
                        updateData(orgId, strNum);
                        //拼接screen_id
                        String screenId = regionCode + exFlag2 + yearStr + strNum;
                        each.setScreeningId(screenId);
                    }
                } else {
                    each.setScreeningId("0000000000000000");
                }

                // 将内镜诊断的文字描述转换成对应的数字描述
                String njzd = each.getNjzd();
                if (njzd.contains(",")) {
                    List<String> nzjdNounNames = Arrays
                        .asList(njzd.split(","))
                        .stream()
                        .filter(str -> StringUtils.isNotEmpty(str))
                        .collect(Collectors.toList());
                    List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounNames(
                        nzjdNounNames);
                    if (!CollectionUtils.isEmpty(infos)) {
                        njzd = infos
                            .stream()
                            .map(tkmEndoscopeDiagnoseNounInfo -> tkmEndoscopeDiagnoseNounInfo.getId())
                            .collect(Collectors.joining(","));
                        each.setNjzd(njzd);
                    } else {
                        each.setNjzd("-1");
                    }
                } else {
                    List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounName(
                        njzd);
                    if (infos.size() > 0) {
                        each.setNjzd(infos
                                         .get(0)
                                         .getId());
                    } else {
                        each.setNjzd("-1");
                    }

                }
            });

        // todo: 此处加入交易编号,以及需要统计出胃镜总量,胃镜总量的计算方式,为当前导入的所有数据的个数
        // todo: 交易号的存在主要是为了找出同一批次下导入的数据,以便于后续的统计
        String checkCode = LocalDate
            .now()
            .format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        importInfoList
            .stream()
            .forEach(each -> {
                each.setTradeNo(tradeNo);
                each.setCheckCode(checkCode);
            });

        importInfoList.forEach(each -> {
            log.info(each.toString());
        });

        // 执行数据写入
        if (importInfoList.size() > 0) {
            int count = systeminitImportInfoService.insertRecords(importInfoList);
            log.info("农癌初始数据上报成功，共{}条数据", count);
        }

        // 标记CerFileImpRecord中的数据为已解析完成
        record.setDisposeStatus(1);
        record.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
        fileImpRecordService.updateRecord(record);

    }

    /**
     * 解析国家农癌初始数据上报
     *
     * @param mqData
     */
    private void handleParseGJCerSystemDataInit(MqData mqData) {
        // 解析农癌初始数据上报
        log.info("解析国家农癌初始数据上报");
        String tradeNo = mqData.getTradeNo();

        // 通过tradeNo查询数据库，获取数据
        CerFileImpRecord record = fileImpRecordService.findByTradeNo(tradeNo);
        // 获取文件所在位置
        String filePath = record.getFilePath();
        // 校正地址
        filePath = getRealFilePath(filePath);

        ImportParams params = new ImportParams();
        params.setTitleRows(1);

        // 解析excel
        List<TkmSystemInitImportDataGJ> list = ExcelImportUtil.importExcel(new File(filePath), TkmSystemInitImportDataGJ.class, params);

        // 数据过滤,国家来源的数据默认都是正确的，仅过滤名称为null的
        list = list.stream().filter(each -> StringUtils.isNotEmpty(each.getName())).collect(Collectors.toList());

        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
                .stream()
                .collect(Collectors.groupingBy(SysDict::getDictType));

        // 将TkmSystemInitImportDataGJ转换成TkmSysteminitImportInfo
        List<TkmSysteminitImportInfo> importInfoList = list
                .stream()
                .map(each -> {
                    TkmSysteminitImportInfo target = getSysteminitImportInfoByGJ(each,keyListMap);
                    return target;
                })
                .collect(Collectors.toList());

        // todo ：对需要导入的数据进行验证，国家导入来源的不需要校验数据

        // 检查是否需要显示诊断详情表
        importInfoList
                .parallelStream()
                .forEach(info -> {
                    Map<String, Boolean> booleanMap = Utils.validateIsHighRisk(info);
                    // 食管详情
                    Boolean sg = booleanMap.get(SUB_DETAIL.SG);
                    info.setIsShowSgDetail(sg ? 1 : 0);
                    // 贲门详情
                    Boolean bm = booleanMap.get(SUB_DETAIL.BM);
                    info.setIsShowBmDetail(bm ? 1 : 0);
                    // 胃详情
                    Boolean wd = booleanMap.get(SUB_DETAIL.WD);
                    info.setIsShowWDetail(wd ? 1 : 0);
                    // 将以上三个详情信息放入extFlag2中
                    String extFlag2 = Arrays
                            .asList(info.getIsShowSgDetail(),
                                    info.getIsShowBmDetail(),
                                    info.getIsShowWDetail())
                            .stream()
                            .map(each -> each.toString())
                            .collect(Collectors.joining("|"));
                    info.setExtFlag2(extFlag2);
                });

        // 执行数据插入前的准备工作
        importInfoList
                .stream()
                .forEach(each -> {
                    each.setId(UuidUtil.get32UUID());
                    each.setCreateBy(record.getCreateBy());
                    each.setDeleted(0);
                    each.setVersion(1);
                    each.setInsertDatetime(new Date(System.currentTimeMillis()));
                    each.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                    // 机构名称 -> 查机构id、机构所在的省市区县的id、extFlag值
                    // 机构名称
                    String institutionName = each.getInstitutionName();
                    SysOrg sysOrg = sysUserService.selectOrgInfoByName(institutionName);

                    if (sysOrg != null) {
                        String extFlag = sysUserService.getUserExtFlag(each,sysOrg);
                        each.setExtFlag(extFlag);
                        String orgId = sysOrg.getId().toString();
                        each.setInstitutionId(orgId);
                        // 设置screening_id
                        //screen_id生成规则,区域id+动态码
                        //规则如下:医院的行政区划(6位)+医院的编号(2位)+年份(2位)+加上医院上报序列号(6位)
                        if (sysOrg.getOrgCode() != null) {
                            //医院的行政区划
                            String regionCode = tkmSysOrgService.getRegionCode(orgId) == null ? ""
                                    : tkmSysOrgService.getRegionCode(orgId);
                            //医院的编号
                            String exFlag2 = tkmSysOrgService.getExFlag2(orgId) == null ? ""
                                    : tkmSysOrgService.getExFlag2(orgId);

                            //年份
                            int year = LocalDate
                                    .now()
                                    .getYear();
                            String yearStr = String.valueOf(year);
                            yearStr = yearStr.substring(yearStr.length() - 2);

                            //医院上报序列号
                            //TODO:此循环不能使用parallelStream(),否则多线程跑会同时未拿到数据然后插入表，达不到预设效果
                            String strNum = getScreenId(orgId);
                            if (StringUtils.isEmpty(strNum)) {
                                insertData(orgId);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + "000001";
                                each.setScreeningId(screenId);
                            } else {
                                updateData(orgId, strNum);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + strNum;
                                each.setScreeningId(screenId);
                            }
                        } else {
                            each.setScreeningId("0000000000000000");
                        }

                        // 将内镜诊断的文字描述转换成对应的数字描述
                        String njzd = each.getNjzd();
                        if (ObjectUtils.isNotEmpty(njzd)) {
                            if (njzd.contains(",")) {
                                List<String> nzjdNounNames = Arrays
                                        .asList(njzd.split(","))
                                        .stream()
                                        .filter(str -> StringUtils.isNotEmpty(str))
                                        .collect(Collectors.toList());
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounNames(
                                        nzjdNounNames);
                                if (!CollectionUtils.isEmpty(infos)) {
                                    njzd = infos
                                            .stream()
                                            .map(tkmEndoscopeDiagnoseNounInfo -> tkmEndoscopeDiagnoseNounInfo.getId())
                                            .collect(Collectors.joining(","));
                                    each.setNjzd(njzd);
                                } else {
                                    each.setNjzd("-1");
                                }
                            } else {
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounName(
                                        njzd);
                                if (infos.size() > 0) {
                                    each.setNjzd(infos
                                            .get(0)
                                            .getId());
                                } else {
                                    each.setNjzd("-1");
                                }
                            }
                        }
                    }
                });

        // 再次过滤extFlag为null数据
        importInfoList = importInfoList.stream()
                .filter(each -> StringUtils.isNotEmpty(each.getExtFlag())||StringUtils.isNotEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        // todo: 此处加入交易编号,以及需要统计出胃镜总量,胃镜总量的计算方式,为当前导入的所有数据的个数
        // todo: 交易号的存在主要是为了找出同一批次下导入的数据,以便于后续的统计
        String checkCode = LocalDate
                .now()
                .format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        importInfoList.stream()
                .forEach(each -> {
                    each.setTradeNo(tradeNo);
                    each.setCheckCode(checkCode);
                });

        importInfoList.forEach(each -> {
            log.info(each.toString());
        });

        // 执行数据写入
        if (importInfoList.size() > 0) {
            int count = systeminitImportInfoService.insertRecords(importInfoList);
            log.info("农癌初始数据上报成功，共{}条数据", count);
        }

        // 标记CerFileImpRecord中的数据为已解析完成
        record.setDisposeStatus(1);
        record.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
        fileImpRecordService.updateRecord(record);
    }

    /**
     * 解析国家农癌详情数据上报
     *
     * @param mqData
     */
    private void handleParseGJCerDetailData(MqData mqData) {
        // 解析国家农癌详情数据上报
        log.info("解析国家农癌详情数据上报");
        String tradeNo = mqData.getTradeNo();

        // 通过tradeNo查询数据库，获取数据
        CerFileImpRecord record = fileImpRecordService.findByTradeNo(tradeNo);
        // 获取文件所在位置
        String filePath = record.getFilePath();
        // 校正地址
        filePath = getRealFilePath(filePath);

        ImportParams params = new ImportParams();
        params.setTitleRows(1);

        // 解析excel（共用初始上报字段）
        List<TkmSystemInitImportDataGJ> list = ExcelImportUtil.importExcel(new File(filePath), TkmSystemInitImportDataGJ.class, params);

        // 数据过滤,国家来源的数据默认都是正确的，仅过滤名称为null的
        list = list.stream().filter(each -> StringUtils.isNotEmpty(each.getName())).collect(Collectors.toList());

        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
                .stream()
                .collect(Collectors.groupingBy(SysDict::getDictType));

        // 将TkmSystemInitImportDataGJ转换成TkmSysteminitImportInfo
        List<TkmSysteminitImportInfo> importInfoList = list
                .stream()
                .map(each -> {
                    TkmSysteminitImportInfo target = getSysteminitImportInfoByGJ(each,keyListMap);
                    return target;
                })
                .collect(Collectors.toList());

        // todo ：对需要导入的数据进行验证，国家导入来源的不需要校验数据

        // 检查是否需要显示诊断详情表
        importInfoList
                .parallelStream()
                .forEach(info -> {
                    Map<String, Boolean> booleanMap = Utils.validateIsHighRisk(info);
                    // 食管详情
                    Boolean sg = booleanMap.get(SUB_DETAIL.SG);
                    info.setIsShowSgDetail(sg ? 1 : 0);
                    // 贲门详情
                    Boolean bm = booleanMap.get(SUB_DETAIL.BM);
                    info.setIsShowBmDetail(bm ? 1 : 0);
                    // 胃详情
                    Boolean wd = booleanMap.get(SUB_DETAIL.WD);
                    info.setIsShowWDetail(wd ? 1 : 0);
                    // 将以上三个详情信息放入extFlag2中
                    String extFlag2 = Arrays
                            .asList(info.getIsShowSgDetail(),
                                    info.getIsShowBmDetail(),
                                    info.getIsShowWDetail())
                            .stream()
                            .map(each -> each.toString())
                            .collect(Collectors.joining("|"));
                    info.setExtFlag2(extFlag2);
                });

        // 执行数据插入前的准备工作
        importInfoList
                .stream()
                .forEach(each -> {
                    each.setId(UuidUtil.get32UUID());
                    each.setCreateBy(record.getCreateBy());
                    each.setDeleted(0);
                    each.setVersion(1);
                    each.setInsertDatetime(new Date(System.currentTimeMillis()));
                    each.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                    // 机构名称 -> 查机构id、机构所在的省市区县的id、extFlag值
                    // 机构名称
                    String institutionName = each.getInstitutionName();
                    SysOrg sysOrg = sysUserService.selectOrgInfoByName(institutionName);

                    if (sysOrg != null) {
                        String extFlag = sysUserService.getUserExtFlag(each,sysOrg);
                        each.setExtFlag(extFlag);
                        String orgId = sysOrg.getId().toString();
                        each.setInstitutionId(orgId);
                        // 设置screening_id
                        //screen_id生成规则,区域id+动态码
                        //规则如下:医院的行政区划(6位)+医院的编号(2位)+年份(2位)+加上医院上报序列号(6位)
                        if (sysOrg.getOrgCode() != null) {
                            //医院的行政区划
                            String regionCode = tkmSysOrgService.getRegionCode(orgId) == null ? ""
                                    : tkmSysOrgService.getRegionCode(orgId);
                            //医院的编号
                            String exFlag2 = tkmSysOrgService.getExFlag2(orgId) == null ? ""
                                    : tkmSysOrgService.getExFlag2(orgId);

                            //年份
                            int year = LocalDate
                                    .now()
                                    .getYear();
                            String yearStr = String.valueOf(year);
                            yearStr = yearStr.substring(yearStr.length() - 2);

                            //医院上报序列号
                            //TODO:此循环不能使用parallelStream(),否则多线程跑会同时未拿到数据然后插入表，达不到预设效果
                            String strNum = getScreenId(orgId);
                            if (StringUtils.isEmpty(strNum)) {
                                insertData(orgId);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + "000001";
                                each.setScreeningId(screenId);
                            } else {
                                updateData(orgId, strNum);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + strNum;
                                each.setScreeningId(screenId);
                            }
                        } else {
                            each.setScreeningId("0000000000000000");
                        }

                        // 将内镜诊断的文字描述转换成对应的数字描述
                        String njzd = each.getNjzd();
                        if (ObjectUtils.isNotEmpty(njzd)) {
                            if (njzd.contains(",")) {
                                List<String> nzjdNounNames = Arrays
                                        .asList(njzd.split(","))
                                        .stream()
                                        .filter(str -> StringUtils.isNotEmpty(str))
                                        .collect(Collectors.toList());
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounNames(
                                        nzjdNounNames);
                                if (!CollectionUtils.isEmpty(infos)) {
                                    njzd = infos
                                            .stream()
                                            .map(tkmEndoscopeDiagnoseNounInfo -> tkmEndoscopeDiagnoseNounInfo.getId())
                                            .collect(Collectors.joining(","));
                                    each.setNjzd(njzd);
                                } else {
                                    each.setNjzd("-1");
                                }
                            } else {
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounName(
                                        njzd);
                                if (infos.size() > 0) {
                                    each.setNjzd(infos
                                            .get(0)
                                            .getId());
                                } else {
                                    each.setNjzd("-1");
                                }
                            }
                        }
                    }
                });

        // 再次过滤extFlag为null数据
        importInfoList = importInfoList.stream()
                .filter(each -> StringUtils.isNotEmpty(each.getExtFlag())||StringUtils.isNotEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        // todo: 此处加入交易编号,以及需要统计出胃镜总量,胃镜总量的计算方式,为当前导入的所有数据的个数
        // todo: 交易号的存在主要是为了找出同一批次下导入的数据,以便于后续的统计
//        String checkCode = LocalDate
//                .now()
//                .format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        importInfoList.stream()
//                .forEach(each -> {
//                    each.setTradeNo(tradeNo);
//                    each.setCheckCode(checkCode);
//                });

        importInfoList.forEach(each -> {
            log.info(each.toString());
        });

        // 执行数据写入
        if (importInfoList.size() > 0) {
            int count = systeminitImportInfoService.insertDetailRecords(importInfoList);
            log.info("农癌详情数据上报导入成功，共{}条数据", count);
        }

        // 标记CerFileImpRecord中的数据为已解析完成
        record.setDisposeStatus(1);
        record.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
        fileImpRecordService.updateRecord(record);
    }

    /**
     * 解析国家农癌详情数据正式库
     *
     * @param mqData
     */
    private void handleParseGJCerDetailOfficial(MqData mqData) {
        // 解析国家农癌详情数据上报
        log.info("解析国家农癌详情数据正式库");
        String tradeNo = mqData.getTradeNo();

        // 通过tradeNo查询数据库，获取数据
        CerFileImpRecord record = fileImpRecordService.findByTradeNo(tradeNo);
        // 获取文件所在位置
        String filePath = record.getFilePath();
        // 校正地址
        filePath = getRealFilePath(filePath);

        ImportParams params = new ImportParams();
        params.setTitleRows(1);

        // 解析excel（共用初始上报字段）
        List<TkmSystemInitImportDataGJ> list = ExcelImportUtil.importExcel(new File(filePath), TkmSystemInitImportDataGJ.class, params);

        // 数据过滤,国家来源的数据默认都是正确的，仅过滤名称为null的
        list = list.stream().filter(each -> StringUtils.isNotEmpty(each.getName())).collect(Collectors.toList());

        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
                .stream()
                .collect(Collectors.groupingBy(SysDict::getDictType));

        // 将TkmSystemInitImportDataGJ转换成TkmSysteminitImportInfo
        List<TkmSysteminitImportInfo> importInfoList = list
                .stream()
                .map(each -> {
                    TkmSysteminitImportInfo target = getSysteminitImportInfoByGJ(each,keyListMap);
                    return target;
                })
                .collect(Collectors.toList());

        // todo ：对需要导入的数据进行验证，国家导入来源的不需要校验数据

        // 检查是否需要显示诊断详情表
        importInfoList
                .parallelStream()
                .forEach(info -> {
                    Map<String, Boolean> booleanMap = Utils.validateIsHighRisk(info);
                    // 食管详情
                    Boolean sg = booleanMap.get(SUB_DETAIL.SG);
                    info.setIsShowSgDetail(sg ? 1 : 0);
                    // 贲门详情
                    Boolean bm = booleanMap.get(SUB_DETAIL.BM);
                    info.setIsShowBmDetail(bm ? 1 : 0);
                    // 胃详情
                    Boolean wd = booleanMap.get(SUB_DETAIL.WD);
                    info.setIsShowWDetail(wd ? 1 : 0);
                    // 将以上三个详情信息放入extFlag2中
                    String extFlag2 = Arrays
                            .asList(info.getIsShowSgDetail(),
                                    info.getIsShowBmDetail(),
                                    info.getIsShowWDetail())
                            .stream()
                            .map(each -> each.toString())
                            .collect(Collectors.joining("|"));
                    info.setExtFlag2(extFlag2);
                });

        // 执行数据插入前的准备工作
        importInfoList
                .stream()
                .forEach(each -> {
                    each.setId(UuidUtil.get32UUID());
                    each.setCreateBy(record.getCreateBy());
                    each.setDeleted(0);
                    each.setVersion(1);
                    each.setInsertDatetime(new Date(System.currentTimeMillis()));
                    each.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                    // 机构名称 -> 查机构id、机构所在的省市区县的id、extFlag值
                    // 机构名称
                    String institutionName = each.getInstitutionName();
                    SysOrg sysOrg = sysUserService.selectOrgInfoByName(institutionName);

                    if (sysOrg != null) {
                        String extFlag = sysUserService.getUserExtFlag(each,sysOrg);
                        each.setExtFlag(extFlag);
                        String orgId = sysOrg.getId().toString();
                        each.setInstitutionId(orgId);
                        // 设置screening_id
                        //screen_id生成规则,区域id+动态码
                        //规则如下:医院的行政区划(6位)+医院的编号(2位)+年份(2位)+加上医院上报序列号(6位)
                        if (sysOrg.getOrgCode() != null) {
                            //医院的行政区划
                            String regionCode = tkmSysOrgService.getRegionCode(orgId) == null ? ""
                                    : tkmSysOrgService.getRegionCode(orgId);
                            //医院的编号
                            String exFlag2 = tkmSysOrgService.getExFlag2(orgId) == null ? ""
                                    : tkmSysOrgService.getExFlag2(orgId);

                            //年份
                            int year = LocalDate
                                    .now()
                                    .getYear();
                            String yearStr = String.valueOf(year);
                            yearStr = yearStr.substring(yearStr.length() - 2);

                            //医院上报序列号
                            //TODO:此循环不能使用parallelStream(),否则多线程跑会同时未拿到数据然后插入表，达不到预设效果
                            String strNum = getScreenId(orgId);
                            if (StringUtils.isEmpty(strNum)) {
                                insertData(orgId);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + "000001";
                                each.setScreeningId(screenId);
                            } else {
                                updateData(orgId, strNum);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + strNum;
                                each.setScreeningId(screenId);
                            }
                        } else {
                            each.setScreeningId("0000000000000000");
                        }

                        // 将内镜诊断的文字描述转换成对应的数字描述
                        String njzd = each.getNjzd();
                        if (ObjectUtils.isNotEmpty(njzd)) {
                            if (njzd.contains(",")) {
                                List<String> nzjdNounNames = Arrays
                                        .asList(njzd.split(","))
                                        .stream()
                                        .filter(str -> StringUtils.isNotEmpty(str))
                                        .collect(Collectors.toList());
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounNames(
                                        nzjdNounNames);
                                if (!CollectionUtils.isEmpty(infos)) {
                                    njzd = infos
                                            .stream()
                                            .map(tkmEndoscopeDiagnoseNounInfo -> tkmEndoscopeDiagnoseNounInfo.getId())
                                            .collect(Collectors.joining(","));
                                    each.setNjzd(njzd);
                                } else {
                                    each.setNjzd("-1");
                                }
                            } else {
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounName(
                                        njzd);
                                if (infos.size() > 0) {
                                    each.setNjzd(infos
                                            .get(0)
                                            .getId());
                                } else {
                                    each.setNjzd("-1");
                                }
                            }
                        }
                    }
                });

        // 再次过滤extFlag为null数据
        importInfoList = importInfoList.stream()
                .filter(each -> StringUtils.isNotEmpty(each.getExtFlag())||StringUtils.isNotEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        // todo: 此处加入交易编号,以及需要统计出胃镜总量,胃镜总量的计算方式,为当前导入的所有数据的个数
        // todo: 交易号的存在主要是为了找出同一批次下导入的数据,以便于后续的统计
//        String checkCode = LocalDate
//                .now()
//                .format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        importInfoList.stream()
//                .forEach(each -> {
//                    each.setTradeNo(tradeNo);
//                    each.setCheckCode(checkCode);
//                });

        importInfoList.forEach(each -> {
            log.info(each.toString());
        });

        // 执行数据写入
        if (importInfoList.size() > 0) {
            int count = systeminitImportInfoService.insertDetailOfficialRecords(importInfoList);
            log.info("农癌详情数据上报导入成功，共{}条数据", count);
        }

        // 标记CerFileImpRecord中的数据为已解析完成
        record.setDisposeStatus(1);
        record.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
        fileImpRecordService.updateRecord(record);
    }

    /**
     * 解析国家农癌初始数据正式库
     *
     * @param mqData
     */
    private void handleParseGJCerSystemDataInitOfficial(MqData mqData) {
        log.info("解析国家农癌初始数据正式库");
        String tradeNo = mqData.getTradeNo();

        // 通过tradeNo查询数据库，获取数据
        CerFileImpRecord record = fileImpRecordService.findByTradeNo(tradeNo);
        // 获取文件所在位置
        String filePath = record.getFilePath();
        // 校正地址
        filePath = getRealFilePath(filePath);

        ImportParams params = new ImportParams();
        params.setTitleRows(1);

        // 解析excel
        List<TkmSystemInitIOfficialmportDataGJ> list = ExcelImportUtil.importExcel(new File(filePath), TkmSystemInitIOfficialmportDataGJ.class, params);

        // 数据过滤,国家来源的数据默认都是正确的，仅过滤名称为null的
        list = list.stream().filter(each -> StringUtils.isNotEmpty(each.getName())).collect(Collectors.toList());

        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
                .stream()
                .collect(Collectors.groupingBy(SysDict::getDictType));

        // 将TkmSystemInitImportDataGJ转换成CerDetaildataImportOfficeInfo
        List<CerDetaildataImportOfficeInfo> importInfoList = list
                .stream()
                .map(each -> {
                    CerDetaildataImportOfficeInfo target = getSysteminitOfficialImportInfoByGJ(each,keyListMap);
                    return target;
                })
                .collect(Collectors.toList());

        // todo ：对需要导入的数据进行验证，国家导入来源的不需要校验数据
        // 检查是否需要显示诊断详情表
        importInfoList
                .parallelStream()
                .forEach(info -> {
                    TkmSysteminitImportInfo initInfo=new TkmSysteminitImportInfo();
                    initInfo.setNjzd(info.getNjzd());
                    Map<String, Boolean> booleanMap = Utils.validateIsHighRisk(initInfo);
                    // 食管详情
                    Boolean sg = booleanMap.get(SUB_DETAIL.SG);
                    info.setIsShowSgDetail(sg ? 1 : 0);
                    // 贲门详情
                    Boolean bm = booleanMap.get(SUB_DETAIL.BM);
                    info.setIsShowBmDetail(bm ? 1 : 0);
                    // 胃详情
                    Boolean wd = booleanMap.get(SUB_DETAIL.WD);
                    info.setIsShowWDetail(wd ? 1 : 0);
                    // 将以上三个详情信息放入extFlag2中
                    String extFlag2 = Arrays
                            .asList(info.getIsShowSgDetail(),
                                    info.getIsShowBmDetail(),
                                    info.getIsShowWDetail())
                            .stream()
                            .map(each -> each.toString())
                            .collect(Collectors.joining("|"));
                    info.setExtFlag2(extFlag2);
                });

        // 执行数据插入前的准备工作
        importInfoList
                .stream()
                .forEach(each -> {
                    each.setId(UuidUtil.get32UUID());
                    each.setCreateBy(record.getCreateBy());
                    each.setDeleted(0);
                    each.setVersion(1);
                    each.setInsertDatetime(new Date(System.currentTimeMillis()));
                    each.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                    // 机构名称 -> 查机构id、机构所在的省市区县的id、extFlag值
                    // 机构名称
                    String institutionName = each.getInstitutionName();
                    SysOrg sysOrg = sysUserService.selectOrgInfoByName(institutionName);
                    if (sysOrg != null) {
                        TkmSysteminitImportInfo info =new TkmSysteminitImportInfo();
                        info.setCreateBy(record.getCreateBy());
                        String extFlag = sysUserService.getUserExtFlag(info,sysOrg);
                        each.setProvinceId(info.getProvinceId());
                        each.setCityId(info.getCityId());
                        each.setDistrictId(info.getDistrictId());
                        each.setExtFlag(extFlag);
                        String orgId = sysOrg.getId().toString();
                        each.setInstitutionId(orgId);
                        // 设置screening_id
                        //screen_id生成规则,区域id+动态码
                        //规则如下:医院的行政区划(6位)+医院的编号(2位)+年份(2位)+加上医院上报序列号(6位)
                        if (sysOrg.getOrgCode() != null) {
                            //医院的行政区划
                            String regionCode = tkmSysOrgService.getRegionCode(orgId) == null ? ""
                                    : tkmSysOrgService.getRegionCode(orgId);
                            //医院的编号
                            String exFlag2 = tkmSysOrgService.getExFlag2(orgId) == null ? ""
                                    : tkmSysOrgService.getExFlag2(orgId);

                            //年份
                            int year = LocalDate
                                    .now()
                                    .getYear();
                            String yearStr = String.valueOf(year);
                            yearStr = yearStr.substring(yearStr.length() - 2);

                            //医院上报序列号
                            //TODO:此循环不能使用parallelStream(),否则多线程跑会同时未拿到数据然后插入表，达不到预设效果
                            String strNum = getScreenId(orgId);
                            if (StringUtils.isEmpty(strNum)) {
                                insertData(orgId);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + "000001";
                                each.setScreeningId(screenId);
                            } else {
                                updateData(orgId, strNum);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + strNum;
                                each.setScreeningId(screenId);
                            }
                        } else {
                            each.setScreeningId("0000000000000000");
                        }

                        // 将内镜诊断的文字描述转换成对应的数字描述
                        String njzd = each.getNjzd();
                        if (ObjectUtils.isNotEmpty(njzd)) {
                            if (njzd.contains(",")) {
                                List<String> nzjdNounNames = Arrays
                                        .asList(njzd.split(","))
                                        .stream()
                                        .filter(str -> StringUtils.isNotEmpty(str))
                                        .collect(Collectors.toList());
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounNames(
                                        nzjdNounNames);
                                if (!CollectionUtils.isEmpty(infos)) {
                                    njzd = infos
                                            .stream()
                                            .map(tkmEndoscopeDiagnoseNounInfo -> tkmEndoscopeDiagnoseNounInfo.getId())
                                            .collect(Collectors.joining(","));
                                    each.setNjzd(njzd);
                                } else {
                                    each.setNjzd("-1");
                                }
                            } else {
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounName(
                                        njzd);
                                if (infos.size() > 0) {
                                    each.setNjzd(infos
                                            .get(0)
                                            .getId());
                                } else {
                                    each.setNjzd("-1");
                                }
                            }
                        }
                    }
                });

        // 再次过滤extFlag为null数据
        importInfoList = importInfoList.stream()
                .filter(each -> StringUtils.isNotEmpty(each.getExtFlag())||StringUtils.isNotEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        // todo: 此处加入交易编号,以及需要统计出胃镜总量,胃镜总量的计算方式,为当前导入的所有数据的个数
        // todo: 交易号的存在主要是为了找出同一批次下导入的数据,以便于后续的统计
//        String checkCode = LocalDate
//                .now()
//                .format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        importInfoList.stream()
//                .forEach(each -> {
//                    each.setTradeNo(tradeNo);
//                    each.setCheckCode(checkCode);
//                });

        importInfoList.forEach(each -> {
            log.info(each.toString());
        });

        // 执行数据写入
        if (importInfoList.size() > 0) {
            int count = systeminitImportInfoService.insertOfficialRecords(importInfoList);
            log.info("农癌数据上报正式库导入成功，共{}条数据", count);
        }

        // 标记CerFileImpRecord中的数据为已解析完成
        record.setDisposeStatus(1);
        record.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
        fileImpRecordService.updateRecord(record);
    }

    public CerDetaildataImportOfficeInfo getSysteminitOfficialImportInfoByGJ(TkmSystemInitIOfficialmportDataGJ each, Map<String, List<SysDict>> keyListMap) {
        CerDetaildataImportOfficeInfo target = new CerDetaildataImportOfficeInfo();
        target.setCountrySource("1");
        target.setIsHaveError(0);
        target.setProvinceName(each.getProvince_name());
        target.setCityName(each.getCity_name());
        target.setDistrictName(each.getDistrict_name());
        target.setInstitutionName(each.getInstitution_name());
        target.setName(each.getName());
        target.setAge(ObjectUtils.isEmpty(each.getAge())?null:Integer.valueOf(each.getAge()));
        target.setSfz(each.getSfz());
        target.setAddr(each.getAddr());
        target.setPhone(each.getPhone());
        target.setMzh(each.getMzh());
        target.setZyh(each.getZyh());
        target.setNjzlTime(each.getNjzl_time());
        target.setNjNum(each.getNj_num());
        target.setPicNums(each.getPic_nums());
        target.setNjzd(each.getNjzd());
        target.setNjStaff(each.getNj_staff());
        target.setVerifyStaff(each.getVerify_staff());
        target.setBlNum(each.getBl_num());
        target.setBlzd(each.getBlzd());
        target.setSgblCode(each.getSgbl_code());
        target.setBmblCode(each.getBmbl_code());
        target.setWblCode(each.getWbl_code());
        target.setSezcCode(each.getSezc_code());
        target.setBlzdStaff(each.getBlzd_staff());
        target.setBlshStaff(each.getBlsh_staff());
        target.setBlbgTime(each.getBlbg_time());
        keyListMap.entrySet().parallelStream().forEach(item->{
            String key = item.getKey();
            List<SysDict> dicts = item.getValue();
            //xb_code 性别 ：1男、2女
            if(Objects.equals("xb_code",key)){
                if (ObjectUtils.isEmpty(each.getSex())) {
                    target.setSex("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getSex())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setSex(sysDict.getDictValue());
                    });
                }
            }
            //zl_fs 诊疗方式
//            target.setZlFs(each.getZl_fs());
            if(Objects.equals("zl_fs",key)){
                if (ObjectUtils.isEmpty(each.getZl_fs())) {
                    target.setZlFs("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getZl_fs())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setZlFs(sysDict.getDictValue());
                    });
                }
            }
            //zldx_ly 对象来源
//            target.setZldxLy(each.getZldx_ly());
            if(Objects.equals("zldx_ly",key)){
                if (ObjectUtils.isEmpty(each.getZldx_ly())) {
                    target.setZldxLy("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getZldx_ly())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setZldxLy(sysDict.getDictValue());
                    });
                }
            }
            //ache 是否无痛
//            target.setAche(each.getAche());
            if(Objects.equals("ache",key)){
                if (ObjectUtils.isEmpty(each.getAche())) {
                    target.setAche("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getAche())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setAche(sysDict.getDictValue());
                    });
                }
            }
            //dye 染色类别
//            target.setDye(each.getDye());
            if(Objects.equals("dye",key)){
                if (ObjectUtils.isEmpty(each.getDye())) {
                    target.setDye("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getDye())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setDye(sysDict.getDictValue());
                    });
                }
            }
            //is_hj 是否活检
//            target.setIsHj(each.getIs_hj());
            if(Objects.equals("is_hj",key)){
                if (ObjectUtils.isEmpty(each.getIs_hj())) {
                    target.setIsHj("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getIs_hj())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setIsHj(sysDict.getDictValue());
                    });
                }
            }
            //Hp hp检测结果
//            target.setHp(each.getHp());
            if(Objects.equals("Hp",key)){
                if (ObjectUtils.isEmpty(each.getHp())) {
                    target.setHp("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getHp())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setHp(sysDict.getDictValue());
                    });
                }
            }
            //hpjcjg hp检测方法
//            target.setHpjcjg(each.getHpjcjg());
            if(Objects.equals("hpjcjg",key)){
                if (ObjectUtils.isEmpty(each.getHpjcjg())) {
                    target.setHpjcjg("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getHpjcjg())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setHpjcjg(sysDict.getDictValue());
                    });
                }
            }
        });

        return target;
    }


    public TkmSysteminitImportInfo getSysteminitImportInfoByGJ(TkmSystemInitImportDataGJ each,Map<String, List<SysDict>> keyListMap) {
        TkmSysteminitImportInfo target = new TkmSysteminitImportInfo();
        target.setCountrySource("1");
        target.setErrorMessage(each.getErrors());
        target.setIsHaveError(ObjectUtils.isEmpty(each.getErrors())?0:1);
        target.setProvinceName(each.getProvince_name());
        target.setCityName(each.getCity_name());
        target.setDistrictName(each.getDistrict_name());
        target.setInstitutionName(each.getInstitution_name());
        target.setName(each.getName());
        target.setAge(each.getAge());
        target.setSfz(each.getSfz());
        target.setAddr(each.getAddr());
        target.setPhone(each.getPhone());
        target.setMzh(each.getMzh());
        target.setZyh(each.getZyh());
        target.setNjzlTime(each.getBlsy_time());
        target.setNjNum(each.getNj_num());
        target.setPicNums(each.getPic_nums());
        target.setNjzd(each.getNjzd());
        target.setNjStaff(each.getNj_staff());
        target.setVerifyStaff(each.getVerify_staff());
        target.setBlNum(each.getBl_num());
        target.setBlzd(each.getBlzd());
        target.setSgblCode(each.getSgbl_code());
        target.setBmblCode(each.getBmbl_code());
        target.setWblCode(each.getWbl_code());
        target.setSezcCode(each.getSezc_code());
        target.setBlzdStaff(each.getBlzd_staff());
        target.setBlshStaff(each.getBlsh_staff());
        target.setBlbgTime(each.getBlbg_time());
        keyListMap.entrySet().parallelStream().forEach(item->{
            String key = item.getKey();
            List<SysDict> dicts = item.getValue();
            //xb_code 性别 ：1男、2女
            if(Objects.equals("xb_code",key)){
                if (ObjectUtils.isEmpty(each.getSex())) {
                    target.setSex("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getSex())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setSex(sysDict.getDictValue());
                    });
                }
            }
            //zl_fs 诊疗方式
//            target.setZlFs(each.getZl_fs());
            if(Objects.equals("zl_fs",key)){
                if (ObjectUtils.isEmpty(each.getZl_fs())) {
                    target.setZlFs("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getZl_fs())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setZlFs(sysDict.getDictValue());
                    });
                }
            }
            //zldx_ly 对象来源
//            target.setZldxLy(each.getZldx_ly());
            if(Objects.equals("zldx_ly",key)){
                if (ObjectUtils.isEmpty(each.getScdx_ly())) {
                    target.setZldxLy("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getScdx_ly())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setZldxLy(sysDict.getDictValue());
                    });
                }
            }
            //ache 是否无痛
//            target.setAche(each.getAche());
            if(Objects.equals("ache",key)){
                if (ObjectUtils.isEmpty(each.getAche())) {
                    target.setAche("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getAche())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setAche(sysDict.getDictValue());
                    });
                }
            }
            //dye 染色类别
//            target.setDye(each.getDye());
            if(Objects.equals("dye",key)){
                if (ObjectUtils.isEmpty(each.getDye())) {
                    target.setDye("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getDye())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setDye(sysDict.getDictValue());
                    });
                }
            }
            //is_hj 是否活检
//            target.setIsHj(each.getIs_hj());
            if(Objects.equals("is_hj",key)){
                if (ObjectUtils.isEmpty(each.getIs_hj())) {
                    target.setIsHj("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getIs_hj())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setIsHj(sysDict.getDictValue());
                    });
                }
            }
            //Hp hp检测结果
//            target.setHp(each.getHp());
            if(Objects.equals("Hp",key)){
                if (ObjectUtils.isEmpty(each.getHp())) {
                    target.setHp("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getHp())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setHp(sysDict.getDictValue());
                    });
                }
            }
            //hpjcjg hp检测方法
//            target.setHpjcjg(each.getHpjcjg());
            if(Objects.equals("hpjcjg",key)){
                if (ObjectUtils.isEmpty(each.getHpjcjg())) {
                    target.setHpjcjg("");
                }else{
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictName().equals(each.getHpjcjg())).findFirst();
                    first.ifPresent(sysDict -> {
                        target.setHpjcjg(sysDict.getDictValue());
                    });
                }
            }
        });
        return target;
    }


    /**
     * 根据是否是docker部署，获取文件路径
     *
     * @param filePath
     * @return
     */
    private String getRealFilePath(String filePath) {
        if (dockerDeploy && volumesConf.getVolumes() != null) {
            String finalFilePath = filePath;
            List<String> arr = Arrays.asList(volumesConf.getVolumes());
            Optional<String> first = arr
                .stream()
                .filter(each -> {
                    // 按照:拆分字符串
                    String[] temp = each.split(":");
                    if (finalFilePath.startsWith(temp[1])) {
                        return true;
                    }
                    return false;
                })
                .findFirst();
            if (first.isPresent()) {
                String[] split = first
                    .get()
                    .split(":");
                filePath = filePath.replace(split[1], split[0]);
            }
        }
        return filePath;
    }

    private TkmSysteminitImportInfo getSysteminitImportInfo(TkmSystemInitImportData each) {
        TkmSysteminitImportInfo target = new TkmSysteminitImportInfo();
        target.setCountrySource("2");
        target.setName(each.getName());
        target.setSex(each.getSex());
        target.setAge(each.getAge());
        target.setSfz(each.getSfz());
        target.setAddr(each.getAddr());
        target.setPhone(each.getPhone());
        target.setMzh(each.getMzh());
        target.setZyh(each.getZyh());
        target.setNjzlTime(each.getNjzl_time());
        target.setZlFs(each.getZl_fs());
        target.setZldxLy(each.getZldx_ly());
        target.setNjNum(each.getNj_num());
        target.setAche(each.getAche());
        target.setDye(each.getDye());
        target.setPicNums(each.getPic_nums());
        target.setIsHj(each.getIs_hj());
        target.setHp(each.getHp());
        target.setHpjcjg(each.getHpjcjg());
        target.setNjzd(each.getNjzd());
        target.setNjStaff(each.getNj_staff());
        target.setVerifyStaff(each.getVerify_staff());
        target.setBlNum(each.getBl_num());
        target.setBlzd(each.getBlzd());
        target.setSgblCode(each.getSgbl_code());
        target.setBmblCode(each.getBmbl_code());
        target.setWblCode(each.getWbl_code());
        target.setSezcCode(each.getSezc_code());
        target.setBlzdStaff(each.getBlzd_staff());
        target.setBlshStaff(each.getBlsh_staff());
        target.setBlbgTime(each.getBlbg_time());
        return target;
    }

    /**
     * 操作生成的screening_id
     */
    public String getScreenId(String orgId) {
        //获取当前年份
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        String yearStr = String.valueOf(year);
        String str = yearStr.substring(yearStr.length() - 2);

        //根据年份和机构id查找是否存在序列号
        String number = cerRecordSerialInfoService.getSerialNumber(orgId, str);
        //如果不为空
        if (StringUtils.isNotEmpty(number)) {
            String anInt = String.valueOf(Integer.parseInt(number) + 1);
            int len = 6;
            int length = anInt.length();
            StringBuilder builder = new StringBuilder();
            for (int i = length; i < len; i++) {
                builder.append("0");
            }
            return builder
                .append(anInt)
                .toString();
        }
        return "";
    }

    /**
     * 插入序列表数据
     *
     * @param orgId 机构主键
     */
    public void insertData(String orgId) {
        //获取当前年份
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        String yearStr = String.valueOf(year);
        String str = yearStr.substring(yearStr.length() - 2);

        CerRecordSerialInfo serialInfo = new CerRecordSerialInfo();
        serialInfo.setId(UuidUtil.get32UUID());
        serialInfo.setOrgId(orgId);
        serialInfo.setYear(str);

        serialInfo.setSerialNumber("000001");
        cerRecordSerialInfoService.insertInfo(serialInfo);
    }

    /**
     * 更新序列表数据
     *
     * @param orgId     机构主键
     * @param serialNum 新的序列
     */
    public void updateData(String orgId, String serialNum) {
        cerRecordSerialInfoService.updateInfo(orgId, serialNum);
    }
}
